
import { registerClass } from "../../../cfw/tools/class_decorator";
import BaseAd from "../../core/base/BaseAd";
import { ResultState, SDKLogicState, SDKState } from "../../SDKDefine";
/**
 * https://minigame.vivo.com.cn/documents/#/api/da/incentive-video-da
 * 注意： 第一次创建视频广告对象时，已自动加载一次广告，请勿重新加载
 * 注意：请在激励视频load成功（触发onLoad）后再调用show
 * 建议：激励视频加载失败后给用户直接发放奖励，或者展示一次其他类型广告并发放奖励
 * 该方法返回的是一个全局单例
 */
@registerClass('VivoRewardAd')
export default class VivoRewardAd extends BaseAd {



    init() {
        this.preload();
    }

    open(): void {
        this.setLogicState(SDKLogicState.open)
        if (this.isState(SDKState.loadSucess)) {
            this.show()
        } else {
            this.create();
        }
    }
    onLoadLogic() {
        if (this.isLogicState(SDKLogicState.open)) {
            
            this.show()
        }
    }

    onClose(res: any) {
        this.setState(SDKState.close)
        console.log('NativeTest onClose ', res)
        if (res && res.isEnded || res === undefined) {
            this.callResultCallback(ResultState.YES)
        } else {
            this.callResultCallback(ResultState.NO)
        }
    }

    show() {
        this.setState(SDKState.show)
        this.setLogicState(SDKLogicState.close)
        this.ad.show().then(() => {
            console.log('激励视频广告展示完成');
        }).catch((err: any) => {
            console.log('激励视频广告展示失败', JSON.stringify(err));
        })
    }


    create(): void {
        this.setState(SDKState.loading)
        if (!this.ad) {
            this.ad = this.sdk.createRewardedVideoAd({ posId: this.adUnitID })
            this.ad.onLoad(this.getFunc(this.onLoad))
            this.ad.onError(this.getFunc(this.onError))
            this.ad.onClose(this.getFunc(this.onClose))
            console.log(' 创建成功')
        } else {
            if (this.ad) {
                this.ad.load();
            }
        }

    }


    destroy() {

    }

}